﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Diagnostics;
using System.Windows;

namespace Master
{
    /*
     * Client is used for this application to handle outgoing connections.
     * For each outgoing connection a client will be created.
     * 
     * @Creator T.T. Dusseldorp
     * @Changes made by:
     *      - A.J. Janssen
     */
    public class Client
    {
        private TcpClient client;
        private NpOutgoing npOutgoing;

        /*
         * For the constructor npOutgoing and a valid ipAddress is required to set up the client
         * Connection will be created inside this constructor
         */
        public Client(NpOutgoing npOutgoing, String ipAddress)
        {
            this.npOutgoing = npOutgoing;
            client = new TcpClient();
            IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse(ipAddress), 1440);
            client.Connect(serverEndPoint);
            npOutgoing.setClient(this);
        }

        /*
         * Function used to send cardetails through the network.
         * If there is no connection the function will throw a message box with an error.
         * and npOutgoing will be disabled again for further use.
         */
        public void Send(CarDetails carDetails)
        {
            try
            {
                NetworkStream clientStream = client.GetStream();
                byte[] buffer = carDetails.Serialize();
                clientStream.Write(buffer, 0, buffer.Length);
                clientStream.Flush();
            }
            catch (Exception e)
            { 
                npOutgoing.Status = NpOutgoingStatus.DISABLED;
                MessageBox.Show("Car could not be send.\nServer closed connection.");
            }
        }

        /*
         * Function used to close the connection at the client side.
         * If the connection is allready closed at the server it will throw a message box with an error.
         */
        public void Close()
        {
            try
            {
                NetworkStream clientStream = client.GetStream();
                client.Close();
            }
            catch (Exception e)
            {
                MessageBox.Show("Connection allready closed at server.");
            }
        }
    }
}
